const vscode = require('vscode');
const { exec } = require('child_process');

/**
 * 扩展激活时调用
 * @param {vscode.ExtensionContext} context
 */
function activate(context) {
    console.log('GoX Go 语法注入扩展已激活');

    // 注册格式化功能
    registerFormattingProviders(context);

    // 注册文件保存处理器
    registerFileHandlers(context);
}

/**
 * 注册格式化提供者
 * @param {vscode.ExtensionContext} context 
 */
function registerFormattingProviders(context) {
    const config = vscode.workspace.getConfiguration('gox');
    
    if (config.get('enableGoFormatting', true)) {
        console.log('启用 GoX 代码块格式化支持');
        
        // 注册文档格式化提供者
        const formatProvider = vscode.languages.registerDocumentFormattingEditProvider(
            { language: 'go' },
            new GoxGoFormattingProvider()
        );
        
        context.subscriptions.push(formatProvider);
    }
}

/**
 * GoX Go 代码块格式化提供者
 */
class GoxGoFormattingProvider {
    provideDocumentFormattingEdits(document, options, token) {
        return new Promise((resolve, reject) => {
            const text = document.getText();
            
            // 查找包含 GoX 语法注入的部分
            const goxPattern = /\b(Query|Exec|QueryRow|Prepare)\s*\(\s*(`[^`]*`)\s*\)/g;
            const edits = [];
            let match;
            
            while ((match = goxPattern.exec(text)) !== null) {
                const fullMatch = match[0];
                const backtickContent = match[2];
                
                // 提取 Go 代码块
                const goBlockPattern = /\{([^{}]*(?:\{[^{}]*\}[^{}]*)*)\}/g;
                let goBlockMatch;
                let formattedBacktickContent = backtickContent;
                
                while ((goBlockMatch = goBlockPattern.exec(backtickContent)) !== null) {
                    const goCode = goBlockMatch[1];
                    const formattedGoCode = this.formatGoCode(goCode, options);
                    
                    if (formattedGoCode !== goCode) {
                        formattedBacktickContent = formattedBacktickContent.replace(
                            `{${goCode}}`,
                            `{${formattedGoCode}}`
                        );
                    }
                }
                
                if (formattedBacktickContent !== backtickContent) {
                    const startPos = document.positionAt(match.index);
                    const endPos = document.positionAt(match.index + fullMatch.length);
                    const range = new vscode.Range(startPos, endPos);
                    
                    const newText = fullMatch.replace(backtickContent, formattedBacktickContent);
                    edits.push(vscode.TextEdit.replace(range, newText));
                }
            }
            
            resolve(edits);
        });
    }
    
    /**
     * 格式化 Go 代码
     * @param {string} goCode 
     * @param {vscode.FormattingOptions} options 
     * @returns {string}
     */
    formatGoCode(goCode, options) {
        // 基础的 Go 代码格式化
        let formatted = goCode
            // 移除多余的空白行
            .replace(/\n\s*\n\s*\n/g, '\n\n')
            // 在大括号后添加换行
            .replace(/\{\s*([^}])/g, '{\n$1')
            // 在大括号前添加换行
            .replace(/([^{])\s*\}/g, '$1\n}')
            // 规范化缩进
            .split('\n')
            .map(line => {
                const trimmed = line.trim();
                if (!trimmed) return '';
                
                // 计算缩进级别
                const indent = options.insertSpaces ? 
                    ' '.repeat(options.tabSize) : '\t';
                
                // 简单的缩进逻辑
                if (trimmed.startsWith('}')) {
                    return trimmed;
                } else if (trimmed.includes('{') && !trimmed.startsWith('if') && !trimmed.startsWith('for')) {
                    return indent + trimmed;
                } else {
                    return indent + trimmed;
                }
            })
            .join('\n');
            
        return formatted;
    }
}

/**
 * 注册文件处理器
 * @param {vscode.ExtensionContext} context 
 */
function registerFileHandlers(context) {
    // 注册文件保存时自动格式化
    const saveHandler = vscode.workspace.onDidSaveTextDocument((document) => {
        const config = vscode.workspace.getConfiguration('gox');
        if (config.get('formatOnSave', false) && document.languageId === 'go') {
            // 触发格式化
            vscode.commands.executeCommand('editor.action.formatDocument');
        }
    });

    context.subscriptions.push(saveHandler);
}

function deactivate() {
    console.log('GoX Go 语法注入扩展已停用');
}

module.exports = {
    activate,
    deactivate
}; 